package com.example.demo.controller;

import java.lang.reflect.Field;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dto.ResultInfo;
import com.example.demo.dto.ResultJson;
import com.example.demo.dto.SearchInfo;
import com.example.demo.mapper.BaseMapper;

@RestController
public class BasicController<T>{

	private BaseMapper getMapper() {
		try {
		Field f=this.getClass().getDeclaredField("mapper");
		f.setAccessible(true);
		return (BaseMapper) f.get(this);
		}catch (Exception e) {
			return null;
		}
	}
	
	@RequestMapping("/list")
	public List<T> list(){
		return getMapper().select(new SearchInfo());
	}
	
	@RequestMapping("/index")
	public ResultInfo index(SearchInfo search,HttpServletRequest req){
		ResultInfo info=new ResultInfo();
		search.initSearch(info,req);
		info.setData(getMapper().select(search));
		return info;
	}
	@RequestMapping("/indexpage")
	public ResultInfo indexpage(SearchInfo search,HttpServletRequest req){
		ResultInfo info=new ResultInfo();
		search.initSearch(info,req);
		info.setData(getMapper().select(search));
		info.setCount(getMapper().selectCount(search));
		return info;
	}
	
	@RequestMapping("/update")
	public ResultJson update(T u){
		getMapper().update(u);
		return new ResultJson(1);
	}
	
	@RequestMapping("/insert")
	public ResultJson insert(T u){
		getMapper().insert(u);
		return new ResultJson(1);
	}
	
	@RequestMapping("/delete")
	public ResultJson delete(int id){
		getMapper().delete(id);
		return new ResultJson(1);
	}
	
	@RequestMapping("/getById")
	public T getById(int id){
		return (T) getMapper().selectById(id);
	}
	
	@RequestMapping("/getarray")
	public String[] getarray(String name){
		try {
		String n=name.split("_")[0];
		String f=name.split("_")[1];
		Class<?> cls=Class.forName("com.example.demo.entity."+n);
		Field fs=cls.getField(f);
		return (String[]) fs.get(null);
		}catch (Exception e) {
			e.printStackTrace();
			return new String[0];
		}
	}
	
}
